package com.yan.network;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import android.content.res.XmlResourceParser;
import android.util.Xml;

import com.yan.activity.Article;
import com.yan.activity.Debug;

public class ParsingManager extends BasicParser implements DTD {
	private static final String TAG = "PARSING_MANAGER";

	public static String buildVersion(String json) {
		if (json.length() > 0) {
			try {
				return json.substring(1, json.length() - 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	// ///////////////RSS READER
	/*
	 * This method is a DOM-based XML parser engine which processes the remote
	 * XML data stream ,breaks it into elements, categorises each element
	 * according to its XML tag and stores thecompletely built element structure
	 * to an ArrayList.
	 */

	/*
	 * public static List<Article> buildArticlesList(InputStream s) {
	 * 
	 * List<Article> rSSItems = new ArrayList<Article>();
	 * 
	 * try {
	 * 
	 * DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	 * DocumentBuilder db = dbf.newDocumentBuilder();
	 * 
	 * Document document = db.parse(s); Element element =
	 * document.getDocumentElement();
	 * 
	 * NodeList nodeList = element.getElementsByTagName("item");
	 * 
	 * if (nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength();
	 * i++) {
	 * 
	 * Element currentElement = (Element) nodeList.item(i);
	 * 
	 * Element _titleE = (Element) currentElement
	 * .getElementsByTagName("title").item(0); Element _descriptionE = (Element)
	 * currentElement .getElementsByTagName("description").item(0); Element
	 * _pubDateE = (Element) currentElement
	 * .getElementsByTagName("pubDate").item(0); Element _linkE = (Element)
	 * currentElement .getElementsByTagName("link").item(0);
	 * 
	 * Element _thumbE = (Element) currentElement
	 * .getElementsByTagName("link").item(0);
	 * 
	 * String _title = _titleE.getFirstChild().getNodeValue(); String
	 * _description = _descriptionE.getFirstChild() .getNodeValue(); Date
	 * _pubDate = new Date(_pubDateE.getFirstChild() .getNodeValue()); String
	 * _link = _linkE.getFirstChild().getNodeValue();
	 * 
	 * String _thumb =
	 * "http://4.bp.blogspot.com/-dqD3kEan1nc/T4KeGsX5M8I/AAAAAAAAAIU/wUECPPYxIrc/s72-c/syma6.jpg"
	 * ;
	 * 
	 * Article rSSItem = new Article(_title, _description, _pubDate, _link,
	 * _thumb);
	 * 
	 * rSSItems.add(rSSItem); } }
	 * 
	 * } catch (Exception e) {
	 * 
	 * 
	 * }
	 * 
	 * return rSSItems;
	 * 
	 * }
	 */
	
	/*public static List<Article> buildArticlesList(InputStream response) {
		
		ArrayList<Article> episodes = null;
		Article current_episode = null;
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Document dom = null;
		try {
			dom = db.parse(response);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}      
        Element docEle = dom.getDocumentElement();
        

        
    	episodes = new ArrayList<Article>();


         NodeList nl = docEle.getElementsByTagName("item");
         
         

         
         if (nl != null && nl.getLength() > 0) {
           for (int i = 0 ; i < nl.getLength(); i++) {
        	   

        	 
        	   
        	 Element entry = (Element)nl.item(i);
           
            	 
            current_episode = new Article();

             Element title = (Element)entry.getElementsByTagName("title").item(0);
             
             current_episode.setTitle(title.getFirstChild().getNodeValue());

             Element link = (Element)entry.getElementsByTagName("link").item(0);

             current_episode.setLink(link.getFirstChild().getNodeValue());

            System.out.println("link="+link.getFirstChild().getNodeValue());
            
            Element description = (Element)entry.getElementsByTagName("description").item(0);

            current_episode.setDescription((description.getFirstChild().getNodeValue()));
            
      

            
            Log.d("ddd","dddesc="+description.getFirstChild().getNodeValue());
            System.out.println("desc="+description.getFirstChild().getNodeValue());
            
            
      

             Element photoUrl = (Element)entry.getElementsByTagName("media:thumbnail").item(0);
             String photoStr = photoUrl.getAttribute("url");
             
             System.out.println("photoStr="+photoStr);
             current_episode.setThumbnailURL(photoStr);


      
	         episodes.add(current_episode);
	    
	    
           //  }
	    
	    
	}
           
  }
         
	
	return episodes;
	
	}*/
	// Feed Parsing Method
	public static List<Article> buildArticlesList(String response) {

		// Array of Episode Objects
		ArrayList<Article> episodes = null;
		
		

		try {
			
			String xml=response.replaceAll("<media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='", "<thumbnail>").replaceAll("' height='72' width='72'/>", "</thumbnail>");


			// Open a Connection to the feed
			XmlPullParser parser = Xml.newPullParser();
			try {
				parser.setInput(new StringReader(xml));
			} finally {

			}

			int event_type = parser.getEventType();
			Article current_episode = null;
			boolean done = false;

			// Parse the feed, start reading throught the feed from top to
			// bottom
			while (event_type != XmlResourceParser.END_DOCUMENT && !done) {

				String tag_name = null;

				switch (event_type) {
				// Found the start of the feed
				case XmlResourceParser.START_DOCUMENT:
					episodes = new ArrayList<Article>();
					break;
				// Found a start tag
				case XmlResourceParser.START_TAG:

					// apply the data to our Episode object based on the tag
					// name
					tag_name = parser.getName();
					if (tag_name.equalsIgnoreCase("item")) {
						current_episode = new Article();
					} else if (current_episode != null) {
						if (tag_name.equals("title")) {
							current_episode.setTitle(parser.nextText());
						} else if (tag_name.equals("pubDate")) {
							current_episode.setPubDate(new Date(parser
									.nextText()));
						} else if (tag_name.equals("link")) {
							current_episode.setLink(parser.nextText());
						} else if (tag_name.equals("description")) {
							current_episode.setDescription(parser.nextText());

						} else if (tag_name.equals("thumbnail")) {
							
							current_episode.setThumbnailURL(parser.nextText());
						}
					}
					break;
				// An end tag has been reached
				case XmlResourceParser.END_TAG:
					tag_name = parser.getName();
					// End of an Episode Item
					if (tag_name.equalsIgnoreCase("item")
							&& current_episode != null) {
						episodes.add(current_episode);
						// Reached the end of all episodes, no more data to
						// collect
					} else if (tag_name.equalsIgnoreCase("channel")) {
						done = true;
					}
					break;
				}
				event_type = parser.next();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		// Return the Episode Array
		return episodes;
	}

	public static List<Article> buildFilmsList(String json) {
		List<Article> films = new ArrayList<Article>();
		Article film;
		int startOffset = json.indexOf("[");
		try {
			JSONArray jsonArray = new JSONArray(json.substring(startOffset));
			int nbJSONObject = jsonArray.length();
			JSONObject jsonObject;
			for (int i = 0; i < nbJSONObject; ++i) {
				jsonObject = jsonArray.getJSONObject(i);
				film = buildFilm(jsonObject);
				films.add(film);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return films;
	}

	/*
	 * public static Article buildFilmDetailed(String json){ Article film;
	 * JSONObject jsonObject; JSONArray jsonArray;
	 * 
	 * //keep only the data of the films int startOffset = json.indexOf("{",
	 * json.indexOf(FILM_DETAILS)); try{ Debug.debugTemporaryLargeString(TAG,
	 * json.substring(startOffset).substring(1515)); jsonObject = new
	 * JSONObject(json.substring(startOffset)); film = buildFilm(jsonObject);
	 * film.setDescription(getString(jsonObject, FILM_DESCRIPTION));
	 * 
	 * int indexPhotos = json.indexOf(FILM_PHOTOS); List<String> photos =
	 * buildPhotos(getBlock(json, json.indexOf('[', indexPhotos), '[', ']'));
	 * film.setPhotos(photos);
	 * 
	 * } catch (Exception e){ e.printStackTrace(); return null; } return film; }
	 */

	public static List<String> buildPhotos(String json) {
		List<String> photos = new ArrayList<String>();
		String photo;
		Debug.debugTemporary(TAG, "buildPhotos json = " + json);
		try {
			int startPhotoOffset;
			int endPhotoOffset;
			// for each block photo url :
			while ((startPhotoOffset = json.indexOf('"')) > -1) {
				Debug.debugTemporary(TAG, "buildPhotos startPhotoOffset = "
						+ startPhotoOffset);
				endPhotoOffset = json.indexOf('"', startPhotoOffset + 1);
				Debug.debugTemporary(TAG, "buildPhotos endPhotoOffset = "
						+ endPhotoOffset);
				photo = json.substring(startPhotoOffset + 1, endPhotoOffset);
				photos.add(photo);
				json = json.substring(endPhotoOffset + 1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return photos;
	}

	private static Article buildFilm(JSONObject jsonObject) {
		/*
		 * Article mArticle = new Article(); try{
		 * mArticle.setName(getString(jsonObject, FILM_NAME));
		 * mArticle.setCertificate(getString(jsonObject, FILM_CERTIFICATE));
		 * mArticle.setDirector(getString(jsonObject, FILM_DIRECTOR));
		 * mArticle.setAuthor(getString(jsonObject, FILM_AUTHOR));
		 * mArticle.setCast(getString(jsonObject, FILM_CAST));
		 * mArticle.setYear(getString(jsonObject, FILM_YEAR));
		 * mArticle.setCategory(getString(jsonObject, FILM_CATEGORY));
		 * mArticle.setRunningTime(getString(jsonObject, FILM_RUNNING_TIME));
		 * mArticle.setStarRating(getInt(jsonObject, FILM_STAR_RATING));
		 * mArticle.setEvents(getInt(jsonObject, FILM_EVENTS));
		 * mArticle.setReleaseDate(getString(jsonObject, FILM_RELEASE_DATE));
		 * mArticle.setThumbSmall(getString(jsonObject, FILM_THUMB_SMALL));
		 * mArticle.setThumbLarge(getString(jsonObject, FILM_THUMB_LARGE));
		 * mArticle.setImage43(getString(jsonObject, FILM_IMAGE_4_3));
		 * mArticle.setImage169(getString(jsonObject, FILM_IMAGE_16_9));
		 * mArticle.setTrailerLow(getString(jsonObject, FILM_TRAILER_LOW));
		 * mArticle.setTrailerMedium(getString(jsonObject,
		 * FILM_TRAILER_MEDIUM)); mArticle.setTrailerHigh(getString(jsonObject,
		 * FILM_TRAILER_HIGH));
		 * 
		 * } catch (Exception e){ e.printStackTrace(); return null; } return
		 * mArticle;
		 */

		return null;
	}

	public static List<Object> buildSearchResult(String json) {
		List<Object> result = new ArrayList<Object>();
		JSONObject jsonObject;
		JSONArray jsonArray;
		int nbJSONObject;
		int startOffset = json.indexOf("[");
		try {
			List<Article> films = new ArrayList<Article>();
			jsonArray = new JSONArray(json.substring(startOffset));
			nbJSONObject = jsonArray.length();
			for (int i = 0; i < nbJSONObject; ++i) {
				jsonObject = jsonArray.getJSONObject(i);
				films.add(buildFilm(jsonObject));
			}

			startOffset = json.indexOf("[", json.indexOf(SEARCH_SCORES));
			jsonArray = new JSONArray(json.substring(startOffset));
			nbJSONObject = jsonArray.length();
			ArrayList<Double> scores = new ArrayList<Double>();
			ArrayList<String> scoresLabel = new ArrayList<String>();
			for (int i = 0; i < nbJSONObject; ++i) {
				int size = scores.size();
				jsonObject = jsonArray.getJSONObject(i);
				double value = jsonObject.getDouble(SEARCH_SCORES_SCORE);
				if (size == 0) {
					scores.add(value);
					scoresLabel.add(jsonObject.getString(SEARCH_SCORES_NAME));
				} else {
					for (int j = 0; j < size; ++j) {
						if (value > scores.get(j)) {
							scores.set(j, value);
							scoresLabel.set(j,
									jsonObject.getString(SEARCH_SCORES_NAME));
						}
					}
					if (size == scores.size()) {
						scores.add(value);
						scoresLabel.add(jsonObject
								.getString(SEARCH_SCORES_NAME));
					}
				}
			}

			for (int i = 0; i < nbJSONObject; ++i) {
				String label = scoresLabel.get(i);
				if (label.equals(SEARCH_TITLES)) {
					Debug.debugTemporary(TAG, "add SEARCH_TITLES");
					result.addAll(films);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}

}